// tslint:disable
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { Component, Input, OnInit } from '@angular/core';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { IonSlides } from '@ionic/angular';
import { RankingModalComponent } from "../../coms/ranking-modal/ranking-modal.component";
import { ModalController } from "@ionic/angular";
import { Platform } from '@ionic/angular';
import { HttpService } from "../../shared/service/http.service";
import { TabsService } from "../../shared/service/tabs.service";
import { RecommendModalComponent } from '../recommend-modal/recommend-modal.component';
import { ModalFromCenterLeave, ModalFromCenterEnter } from 'src/app/utils/transitions';
import { ProcessLoginDataService } from 'src/app/shared/service/process-login-data.service';
import { MyBiconModalComponent } from '../my-bicon-modal/my-bicon-modal.component';
import { BusinessModalComponent } from '../business-modal/business-modal.component';
import { ShareService } from 'src/app/shared/service/share.service';
@Component({
  selector: 'app-bicon-links',
  templateUrl: './bicon-links.component.html',
  styleUrls: ['./bicon-links.component.scss'],
})
export class BiconLinksComponent implements OnInit {

  @Input() tagData;
  mask: string;
  aWidth: string;
  cssStr = {};
  // 控制是否换行
  cssWrap = {};
  // 控制li宽度
  liWidth = {};
  largeData: any = [];
  idx: any = 1;
  title = "信息大厅";
  slideOpts = {
    initialSlide: 0, // 默认显示第几个slide
    speed: 400
  };
  getPhoneSubmitId: any; // 获取手机号码的submitId
  loginSubmitId: any; // 登录的submitId

  leftBottomLabel2: any;
  leftBottomLabelItem: any;

  boxIconBtn: any; // 蜂喔商户1.6.21
  tipsIconBtn: any; // 蜂喔商户1.6.21
  openFlag = true;
  leftBottomTips: any;

  constructor(
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private httpService: HttpService,
    private processLoginData: ProcessLoginDataService,
    private shareService: ShareService,
    private modalController: ModalController,
    private platform: Platform
  ) { }

  ngOnInit() {

    // console.log(this.tagData);

    // // 蜂喔商户1.6.21 新增 按钮  
    // 支持多个
    // 
    if (this.tagData.data
      && this.tagData.data.data
      && this.tagData.data.data.data
      && this.tagData.data.data.data.data) {
      const array = this.tagData.data.data.data.data;
      let link;
      if (this.tagData.data.data.data.link) {
        link = this.tagData.data.data.data.link;
      }
      this.tagData.data.data.data.data = null;
      this.tagData.data.data.data = array;

    }

    //1.6.35 版本新增支持limit
    if (this.tagData.data && this.tagData.data.data && this.tagData.data.data.limit !== undefined) {
      this.tagData['limit'] = this.tagData.data.data.limit;
    }

    // boxIconLink
    if (this.tagData.data.data.linkItem && this.tagData.data.data.linkItem[0]) {
      this.boxIconBtn = this.tagData.data.data.linkItem[0];
    }

    if (this.tagData.data.data.linkItem && this.tagData.data.data.linkItem[1]) {
      this.tipsIconBtn = this.tagData.data.data.linkItem[1];
    }

    if (this.tagData.data.data.cssStyle) {
      // 不知道为什么这么写，注释掉
      // const cssStyles = this.tagData.data.data.cssStyle.split(",").join(',').split(';');
      const cssStyles = this.tagData.data.data.cssStyle.split(","); // 感觉这么写是对的

      for (let i = 0; i < cssStyles.length; i++) {
        const cssStrs = cssStyles[i].split(":");
        this.cssStr[cssStrs[0]] = cssStrs[1];
      }

      for (let i = 0; i < cssStyles.length; i++) {
        if (cssStyles[i].indexOf('flex-wrap') !== -1 || cssStyles[i].indexOf('justify-content') !== -1) {
          const cssStrs = cssStyles[i].split(":");
          this.cssWrap[cssStrs[0]] = cssStrs[1];
        }
      }

      for (let i = 0; i < cssStyles.length; i++) {
        if (cssStyles[i].indexOf('liWidth') !== -1) {
          const cssStrs = cssStyles[i].split(":");
          this.liWidth['width'] = cssStrs[1];
        }
      }
    }
    this.mask = this.tagData.isMask + 'px';
    this.aWidth = 100 / this.tagData.data.data.data.length + '%';
    const element = this.tagData.data.data.data;
    if (this.tagData.data.data.data && this.tagData.data.data.data.length > 8) {

      if (this.tagData.data.data.disableSlidePage !== undefined) {
        this.largeData.push(element);
        this.tagData.data.showSlider = 'false';
      } else {
        this.sliceElement(element);
      }
    } else if (this.tagData.data.data && this.tagData.data.data.style
      && this.tagData.data.data.style === 'styleLimit4') {
      this.sliceElement(element);
    }

    if (this.tagData.data.data !== undefined) {
      if (this.tagData.data.data.leftBottomLabel !== undefined && this.tagData.data.data.leftBottomLabel.length > 1) {
        this.leftBottomLabel2 = this.tagData.data.data.leftBottomLabel[1];

      }
    }
  }

  // 1.6.35 合并元素
  sliceElement(element) {
    if (this.tagData.data.data.singlePageSize) {
      const size = Number(this.tagData.data.data.singlePageSize);
      if (element.slice(0, size).length > 0) {
        this.largeData.push(element.slice(0, size));
      }
      if (element.slice(size, size * 2).length > 0) {
        this.largeData.push(element.slice(size, size * 2));
      }
      if (element.slice(size * 2, size * 3).length > 0) {
        this.largeData.push(element.slice(size * 2, size * 3));
      }
      if (element.slice(size * 3, size * 4).length > 0) {
        this.largeData.push(element.slice(size * 3, size * 4));
      }
    } else {
      if (element.slice(0, 8).length > 0) {
        this.largeData.push(element.slice(0, 8));
      }
      if (element.slice(8, 16).length > 0) {
        this.largeData.push(element.slice(8, 16));
      }
      if (element.slice(16, 24).length > 0) {
        this.largeData.push(element.slice(16, 24));
      }
      if (element.slice(24, 32).length > 0) {
        this.largeData.push(element.slice(24, 32));
      }
    }
  }

  jumpToPage(item) {
    // 1.9.0 改动版本 免费设计配置oneLogin走极光一键登录 
    if (item.action && item.action === 'oneLogin') {
      if (!this.platform.is('mobileweb') && (this.platform.is('ios') || this.platform.is('android'))) {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.buttonLink ? item.buttonLink.params : item.link.params // 1.9.15 新增版本
        };
        // 未登录才会跳转到一键登录
        if (item.isLogin === false) {
          this.processLoginData.jVerificationLogin(params, this.getPhoneSubmitId, this.loginSubmitId, (msg) => {
            // 其他登录
            if (window['otherButton'] !== null && window['otherButton'] !== undefined) {
              const link = window['otherButton'];
              this.pageModalService.openPage(link);
              window['otherButton'] = null;
            } else if (window['wxlinkButton'] !== null && window['wxlinkButton'] !== undefined) {
              const link = window['wxlinkButton'];
              this.shareService.gotoAutoLoginWithWechatOpenId(this.appGlobalService.clientType === 'js' ? 2 : 1, (res) => {
                if (res && res.isLogin !== undefined && res.isLogin) {

                  // 接口还未返回该参数故用默认值
                  this.processLoginData.processLoginData(this.appGlobalService.loginRes, this.appGlobalService.loginRes.data.account, this.appGlobalService.loginRes.params);
                } else if (res && res.isLogin !== undefined && !res.isLogin) {
                  console.log('还未绑定!');
                  if (link) {
                    // 跳转到普通登录页面
                    this.pageModalService.openPage(link);
                  }
                }
              });
              window['wxlinkButton'] = null;
            } else {
              if (msg === null || msg === 6002) {
                return; //取消
              } else {
                this.pageModalService.openPage(item.buttonLink);
              }
            }
          });
        } else {
          // 已经登录之后
          this.pageModalService.openPage(item.link);
        }
      } else {
        this.pageModalService.openPage(item.buttonLink);
      }
    } else if (item.action && item.action === 'modal') {
      if (item.className) {
        this.openMyBiconModal(item.className, item);
      } else {
        this.pageModalService.openPage(item.link);
      }
    } else if (item.action && item.action === 'secondLink') {
      this.pageModalService.openPage(item.link);
    } else {
      // 其他按钮时下期功能，点击提示"item.tip"
      if (item.tip || item.message) {
        this.appGlobalService.showToast(item.tip ? item.tip : item.message ? item.message : '正在快马加鞭开发中', 2000, "middle");
        return;
      }
      this.normalJumpPage(item);
    }



  }


  normalJumpPage(item) {
    if (item && item.link.target) {
      // fix bug 3206 http://chandao.xwkj.local:8018/bug-view-3206.html
      item.count = 0;
      if (item.link.params && item.link.params.showName) {
        sessionStorage.setItem('showName', item.link.params.showName); // 我的业务点击
      }
      if (item.buttonLink && !localStorage.getItem('firstAiSearch')) {
        localStorage.setItem('firstAiSearch', 'firstAiSearch');
        this.pageModalService.openPage(item.buttonLink);

      } else {
        this.pageModalService.openPage(item.link);
      }

    }
  }


  getprevIndex() {
    this.idx -= 1;
  }

  getnextIndex() {
    this.idx += 1;
  }

  getIndex(slides: IonSlides) {
    const that = this;
    slides.getActiveIndex().then(index => {
      that.idx = index;
      if (that.idx <= that.tagData.data.data.length) {
        that.idx = index;
      } else {
        that.idx = 1;
      }
    });
  }


  openModal(link) {
    try {
      if (link.type && link.type === 'modal') {
        this.openRankingModal("recommend-modal", link);
      } else if (link.type && link.type === 'businessModal') {
        this.openBusinessModal("recommend-modal-auto-heigth", link);
      } else if (link.type && link.type === 'rankModal') {
        this.openRankingModal2("ranking-modal", link);
      } else {
        this.pageModalService.openPage(link);
      }
    } catch (error) {

    }
  }


  // ranking-modal
  async openRankingModal2(className, link) {
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: link.target,
      params: link.params,
    };
    this.httpService.post("application/page", params, async (res) => {
      const tagData = JSON.parse(res.script).views[0].tags[0].data;
      // "ranking-modal"
      const modal = await this.modalController.create({
        showBackdrop: true,
        cssClass: className,
        component: RankingModalComponent,
        componentProps: { tagData },
      });
      await modal.present();
      // 监听销毁的事件
      const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    });
  }

  async openBusinessModal(className, item) {
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: item.target,
      params: item.params
    };
    this.httpService.post('application/page', params, async res => {
      const tagData = JSON.parse(res.script).views[0].tags[0].data;
      // "ranking-modal"
      const modal = await this.modalController.create({
        showBackdrop: true,
        cssClass: className,
        component: BusinessModalComponent,
        animated: false,
        componentProps: { tagData }
      });
      await modal.present();
      // 监听销毁的事件
      const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    });
  }

  async openRankingModal(className, item) {
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: item.target,
      params: item.params
    };
    this.httpService.post('application/page', params, async res => {
      const tagData = JSON.parse(res.script).views[0].tags[0].data;
      // "ranking-modal"
      const modal = await this.modalController.create({
        showBackdrop: true,
        cssClass: className,
        component: RecommendModalComponent,
        componentProps: { tagData },
        leaveAnimation: ModalFromCenterLeave,
        enterAnimation: ModalFromCenterEnter
      });
      await modal.present();
      // 监听销毁的事件
      const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    });
  }

  openLink(link) {
    try {
      if (link) {
        const tmpSessionId = localStorage.getItem('sessionId');
        const pageParams = {
          pageId: link.target,
          params: link.params,
          sessionId: tmpSessionId
        };
        this.appGlobalService.goToForward(pageParams);
      }
    } catch (error) {

    }
  }

  async openMyBiconModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        const modal = await this.modalController.create({
          showBackdrop: true,
          cssClass: className,
          animated: false,
          component: MyBiconModalComponent,
          componentProps: { tagData }
        });
        await modal.present();
        // 监听销毁的事件
        const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }

  }

  expandText(e) {
    e.stopPropagation();
    this.openFlag = !this.openFlag;
  }
}
